#include <stdio.h>
#include <string.h>
#include <unistd.h>
#include <stdlib.h>
#include <sys/types.h>
#include <sys/wait.h>
#include <sys/stat.h>
#include <fcntl.h>

#define BUFSIZE	128


int main(int argc, char **argv)
{
    int pfd[2] = {}; // 管道通信文件描述符
    pid_t pid;
    int fd;
    char buf[BUFSIZE] = {};
    int ret;

    if (argc < 2) 
        return 1;

    if (-1 == pipe(pfd)) {
        perror("pipe()");
        return 1;
    }

    fd = open("./music.mp3", O_RDWR);

    if (-1 == fd) {
        perror("open()");
        return 1;
    }

    pid = fork();

    if (-1 == pid) {
        perror("fork()");
        return 1;
    }

    if (0 == pid) {

        close(pfd[1]); // 子进程关闭管道写端

        dup2(pfd[0], 0); // 0号重定向到pfd[0]

        execlp("mplayer", "mplayer", "-", NULL);

        perror("execlp()");
        close(pfd[0]);
        return 0;
    }

    close(pfd[0]); // 父进程关闭管道读端


    while ((ret = read(fd, buf, BUFSIZE)) > 0) {
        write(pfd[1], buf, ret);
        memset(buf, 0, BUFSIZE);
    }

    if (-1 == ret) {
        perror("read()");
        return 1;
    }

    close(pfd[1]);

    wait(NULL);

    close(fd);

    return 0;
}

